package com.whut.monitor.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author qing
 * websocket访问接口
 */
@Component
@ServerEndpoint(value="/websocket/{deviceNum}")
public class PollWebSocketServlet {

    public static final Map<String,Set<Session>> CLIENTS = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(@PathParam("deviceNum") String deviceNum, Session session) {
        if (CLIENTS.get(deviceNum)==null){
            Set<Session> sessions = new HashSet<Session>();
            sessions.add(session);
            CLIENTS.put(deviceNum,sessions);
        }else {
            CLIENTS.get(deviceNum).add(session);
        }
        System.out.println("WebSocketOpen: deviceNum=" + deviceNum + " size=" + CLIENTS.get(deviceNum).size());
    }

    @OnMessage
    public void onMessage(String message,@PathParam("deviceNum") String deviceNum) {
        System.out.println("WebSocketOnMessage: deviceNum=" + deviceNum + " message=" + message);
    }

    @OnClose
    public void onClose(@PathParam("deviceNum") String deviceNum, Session peer) {
        System.out.println("WebSocketClose: deviceNum=" + deviceNum + " Session=" + peer);
        Set<Session> sessions = CLIENTS.get(deviceNum);
        synchronized (sessions){
            sessions.remove(peer);
        }
        if (sessions.size()<=0) {
            CLIENTS.remove(deviceNum);
        }
    }

    public boolean sendMes(String deviceNum,String message) {
//        System.out.println("WebSocketSendMes: deviceNum=" + deviceNum + " message=" + message);
        try {
            Set<Session> sessions = CLIENTS.get(deviceNum);
            if (sessions==null) {
                return true;
            }
            synchronized (sessions){
                for (Session session : sessions) {
                    session.getBasicRemote().sendText(message);
                }
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
}
